//
//  MTCClienterDetailViewController.m
//  ERP
//
//  Created by QA on 15/9/17.
//  Copyright (c) 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MTCClienterDetailViewController.h"
#import "NSDictionary+DataFormat.h"
#import "NSMutableDictionary+Format.h"
#import "WebServiceCommonRequest.h"
#import "NSKeyedArchiverUserLogin.h"

#import "AutoTextTableViewCell.h"
#import "MTContractListViewCell.h"

#import "MTCContractDetailViewController.h"
#import "MTCCraeteClienterViewController.h"

@interface MTCClienterDetailViewController ()

@property (nonatomic,strong) NSDictionary *clienterModelDic;

@property (nonatomic,strong) NSArray *orderContractData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@property (nonatomic,strong) NSMutableArray *clienterArray;
@property (nonatomic,strong) NSMutableArray *otherArray;

@end

@implementation MTCClienterDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle:@"客户信息明细"];
        
        BOOL KHDA = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_KHDA_BJKH"].count;
        if(KHDA){
            UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(createClienterSelector:)];
            self.navigationItem.rightBarButtonItem = leftButton;
        }
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    NSDictionary *dic = object;
    self.clienterModelDic = dic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.orderContentState = 0;
    [self setShowValueView:self.clienterModelDic];
    
    //获取所有合同
    [self getClienterContractOrderInfo];
}

- (void)setShowValueView:(NSDictionary*)dic
{
    self.clienterArray = [NSMutableArray array];
    [self addContractInfoKey:@"客户编号" toKey:@"客户编号：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"客户名称" toKey:@"客户名称：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"客户法人" toKey:@"客户法人：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"电话" toKey:@"联系电话：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"传真" toKey:@"传       真：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"注册资金" toKey:@"注册资金：" defaults:@"未知" format:@"%@元" form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"注册日期" toKey:@"注册日期：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"注册地" toKey:@"注  册  地：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"开户银行" toKey:@"开户银行：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"公司账户" toKey:@"公司账户：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"客户星级" toKey:@"客户星级：" defaults:@"未知" format:@"%@星" form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"办公地址" toKey:@"办公地址：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"经营范围" toKey:@"经营范围：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"税号" toKey:@"公司税号：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    [self addContractInfoKey:@"财务联系人" toKey:@"财务联系人：" defaults:@"未知" format:nil form:dic toArray:_clienterArray];
    
    self.otherArray = [NSMutableArray array];
    [self addContractInfoKey:@"快递地址" toKey:@"快递地址：" defaults:@"无" format:nil form:dic toArray:_otherArray];
    [self addContractInfoKey:@"备注" toKey:@"备      注：" defaults:@"无" format:nil form:dic toArray:_otherArray];
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}


#pragma mark - 网络客户合同信息
- (void)getClienterContractOrderInfo
{
    //判断是否需要获取订单
    if(!self.clienterModelDic) return;
    NSString *khbh = [self.clienterModelDic objectFormatStringForKey:@"客户编号"];
    if(!(khbh && khbh.length >0)) khbh = @"***未知***";
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_HTLB_LIST_20170117"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"起始条数" value:@0];
    [content addParameterKey:@"结束条数" value:@100];
    [content addParameterKey:@"合同性质" value:@""];
    [content addParameterKey:@"审核状态" value:@""];
    [content addParameterKey:@"合同状态" value:@""];
    [content addParameterKey:@"分发状态" value:@""];
    [content addParameterKey:@"客户编号" value:khbh];
    [content addParameterKey:@"检索条件" value:@""];
    [content addParameterKey:@"合同ID" value:@""];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            self.orderContractData = firstArray;
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
    
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 2) {
        NSInteger count = self.orderContractData.count;
        return count > 0 ? count : 1;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //合同结算信息
    if (indexPath.section == 0 && indexPath.row == 0){
        NSString *identifier = [NSString stringWithFormat:@"MTCClienterDetailOne%ld",(long)indexPath.section];
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setDataArray:self.clienterArray];
        return cell;
        
    } else if (indexPath.section == 1 && indexPath.row == 0){
        NSString *identifier = [NSString stringWithFormat:@"MTCClienterDetailTwo%ld",(long)indexPath.section];
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setDataArray:self.otherArray];
        return cell;
        
    } else if (indexPath.section == 2){
        if (self.orderContentState == 3) {
            static NSString *CellIdentifierOne = @"MTContractListViewCell";
            MTContractListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
            if (!cell) cell = [[MTContractListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
            
            //添加分割线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 81.5, SuperWidth, 0.5)];
            lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
            [cell.contentView addSubview:lineView];
            
              //车辆信息设置
            NSDictionary *model = [self.orderContractData objectAtIndex:indexPath.row];
            cell.HTBHLabel.text = [model objectFormatStringForKey:@"合同编号" defaults:@"未知"];
            cell.HTMCLabel.text = [model objectFormatStringForKey:@"合同名称" defaults:@"未知"];
            cell.HTXZLabel.text = [model objectFormatStringForKey:@"合同性质" defaults:@"未知"];
            cell.LJFLLabel.text = [model objectFormatStringForKey:@"合同总量" format:@"累计%@方" defaults:@"未知"];
            cell.HTJDLabel.text = [model objectFormatStringForKey:@"完成进度" format:@"%@%%" defaults:@"未知"];
            cell.threeLabel.text = [model objectFormatStringForKey:@"业务人员" defaults:@"未知"];
            cell.fourLabel.text = [model objectFormatStringForKey:@"签订日期" defaults:@"未知"];
            cell.rightFourLabel.text = [model objectFormatStringForKey:@"合同状态" defaults:@"未知"];
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCClienterDetailHT"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(cell.frame.size.width/2, 28.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"未找到合同";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载合同信息失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = ThemeColorBlue;
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if(section == 0){
        lable.text = @"客户基本信息";
    } else if(section == 1){
        lable.text = @"其他信息";
    } else if(section == 2){
        lable.text = @"客户合同";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.clienterArray];
        return cell.contentView.frame.size.height;
        
    }  else if (indexPath.section == 1 && indexPath.row == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.otherArray];
        return cell.contentView.frame.size.height;
    }
    
    if (self.orderContractData.count > 0) return 82;
    else return 56;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 2) {
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getClienterContractOrderInfo];
            
        } else if(self.orderContentState == 3) { //加载成功
            NSDictionary *model = [self.orderContractData objectAtIndex:indexPath.row];
            MTCContractDetailViewController *viewController = [[MTCContractDetailViewController alloc] initWithModel:model];
            [self.navigationController pushViewController:viewController animated:YES];
        }
    }
}

#pragma mark -
#pragma mark Button Selector

- (void)createClienterSelector:(id)sender
{
    MTCCraeteClienterViewController *viewController = [[MTCCraeteClienterViewController alloc] initWithValue:self.clienterModelDic];
    viewController.backResultDelagate = self;
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if (!backValue) return;
    [self setShowValueView:backValue];
    
    //更新列表页面
    if (self.backResultDelagate) {
        NSArray *backResult = @[self.clienterModelDic,backValue];
        [self.backResultDelagate backResultDataKey:self.key dataValue:backResult];
        self.clienterModelDic = backValue;
    }
}

@end
